package com.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

// PetService.java
public class PetService {
    public void addPet(Pet pet) throws Exception {
        String sql = "INSERT INTO pet(name, type, age, gender, price) VALUES(?,?,?,?,?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, pet.getName());
            pstmt.setString(2, pet.getType());
            pstmt.setInt(3, pet.getAge());
            pstmt.setString(4, pet.getGender());
            pstmt.setDouble(5, pet.getPrice());
            pstmt.executeUpdate();
        }
    }

    public List<Pet> getAllPets(String orderBy) throws Exception {
        String sql = "SELECT * FROM pet ORDER BY " + orderBy;
        List<Pet> pets = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement()) {
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Pet pet = new Pet();
                pet.setId(rs.getInt("id"));
                pet.setOwnerId(rs.getInt("owner_id"));
                pet.setName(rs.getString("name"));
                pet.setType(rs.getString("type"));
                pet.setAge(rs.getInt("age"));
                pet.setGender(rs.getString("gender"));
                pet.setPrice(rs.getDouble("price"));
                pets.add(pet);
            }
        }
        return pets;
    }

    public void purchasePet(int userId, int petId) throws Exception {
        Connection conn = DBUtil.getConnection();
        try {
            conn.setAutoCommit(false);

            // 检查宠物是否存在且未售出
            Pet pet = getPetById(petId);
            if (pet == null) throw new Exception("宠物不存在");
            if (pet.getOwnerId() != null) throw new Exception("宠物已售出");

            // 检查用户积分
            User user = getUserById(userId);
            if (user.getPoints() < pet.getPrice()) throw new Exception("积分不足");

            // 更新宠物主人
            String updatePet = "UPDATE pet SET owner_id = ? WHERE id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(updatePet)) {
                pstmt.setInt(1, userId);
                pstmt.setInt(2, petId);
                pstmt.executeUpdate();
            }

            // 扣除积分
            String updateUser = "UPDATE user SET points = points - ? WHERE id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(updateUser)) {
                pstmt.setDouble(1, pet.getPrice());
                pstmt.setInt(2, userId);
                pstmt.executeUpdate();
            }

            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            throw e;
        } finally {
            conn.setAutoCommit(true);
        }
    }
}